import { Request, Response, NextFunction } from 'express';
import { ErrorCode, ApiError } from '@/types';
import { createApiError } from '@/utils/response';

export const errorHandler = (
  err: Error,
  _req: Request,
  res: Response,
  _next: NextFunction
): void => {
  console.error('Error:', err);

  let apiError: ApiError = createApiError(
    ErrorCode.INTERNAL_SERVER_ERROR,
    'Internal server error'
  );

  // Handle different error types
  if (err.name === 'ValidationError') {
    apiError = createApiError(
      ErrorCode.VALIDATION_ERROR,
      'Validation failed',
      err.message
    );
    res.status(400).json(apiError);
    return;
  }

  if (err.name === 'CastError') {
    apiError = createApiError(
      ErrorCode.VALIDATION_ERROR,
      'Invalid ID format'
    );
    res.status(400).json(apiError);
    return;
  }

  if (err.name === 'MongoServerError' && (err as any).code === 11000) {
    apiError = createApiError(
      ErrorCode.DUPLICATE_RESOURCE,
      'Resource already exists'
    );
    res.status(409).json(apiError);
    return;
  }

  // Default error response
  res.status(500).json(apiError);
};